(function (window, undefined) {
  //蛇对象
  /* 
    1，蛇；蛇头（red,一节） + 蛇身（blue, 两节），整体三节
    2，蛇的属性：运动方向direction: rigth,  元素数组elements；
    */
  const abso = "absolute";
  var that = null;
  function Snake(option) {
    let ops = option instanceof Object ? option : {};
    this.width = ops.width || 20;
    this.height = ops.height || 20;
    //蛇头，蛇身
    this.body = [
      { x: 3, y: 2, backgroundColor: "red" },
      { x: 2, y: 2, backgroundColor: "blue" },
      { x: 1, y: 2, backgroundColor: "blue" },
    ];
    //定位方式
    this.position = abso;
    //默认运动方向
    this.direction = ops.direction || "right";
    //存储创建的元素对象
    this.elements = [];
    //保存this
    that = this;
  }
  Snake.prototype.render = function (map) {
    for (let i = 0, len = this.body.length; i < len; i++) {
      let div = document.createElement("div");
      div.style.position = this.position;
      div.style.width = this.width + "px";
      div.style.height = this.height + "px";
      div.style.backgroundColor = this.body[i].backgroundColor;
      div.style.left = this.width * this.body[i].x + "px";
      div.style.top = this.height * this.body[i].y + "px";
      map.appendChild(div);
      this.elements.push(div);
    }
  };
  Snake.prototype.move = function () {
    //每移动一次，蛇身跟随蛇头移动，即蛇身逐节等于上一节坐标
    for (var i = this.body.length - 1; i > 0; i--) {
      this.body[i].x = this.body[i - 1].x;
      this.body[i].y = this.body[i - 1].y;
    }
    //记录蛇头
    let head = this.body[0];
    //记录蛇头坐标
    // this.HX = head.x;
    // this.HY = head.y;
    switch (this.direction) {
      case "top":
        head.y -= 1;
        break;
      case "right":
        head.x += 1;
        break;
      case "bottom":
        head.y += 1;
        break;
      case "left":
        head.x -= 1;
        break;
      default:
        break;
    }
  };
  Snake.prototype.remove = function (map) {
    //从蛇尾开始移动
    for (var i = this.elements.length - 1; i >= 0; i--) {
      map.removeChild(this.elements[i]);
    }
    this.elements = [];
  };
  window.Snake = Snake;
})(window, undefined);
// const map = document.getElementById("map");
// let snake = new Snake();
// snake.render(map);
// let timer = setInterval(() => {
//   snake.move(map);
//   snake.remove(map);
//   snake.render(map);
//   if (snake.HX <= 0 || snake.HX >= map.clientWidth / snake.width - 1 || snake.HY <= 0 || snake.HY >= map.clientHeight / snake.height - 1) {
//     clearInterval(timer);
//     alert("game over!");
//   }
// }, 200);
